<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <PageTools :show-before="true">
        <template #before>共{{ page.total }}条记录</template>
        <template #after>
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportExcleFn"
            >导出</el-button
          >
          <el-button
            size="small"
            type="primary"
            @click.native="showDialog = true"
            >新增员工</el-button
          >
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable type="index" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{row}">
              <el-image
                @click.native="previewFn(row.staffPhoto)"
                style="width: 100px; height: 100px"
                :src="row.staffPhoto"
                fit="contain"
                :lazy="true"
                :preview-src-list="previewArr"
              />
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column
            label="聘用形式"
            :formatter="formatterTypeFn"
            sortable
            prop="formOfEmployment"
          />
          <!-- :formatter="formatterDateFn" -->
          <el-table-column label="部门" sortable prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable prop="enableState">
            <template #default="{row}">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" /> </template
          ></el-table-column>
          <el-table-column label="操作" prop="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="handleShowRole(row.id)"
                >角色</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="delFn(row.id)"
                :disabled="!checkPermFn()"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页组件 -->
          <el-pagination
            :current-page="page.page"
            :page-sizes="page.pagesizes"
            :page-size="page.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <AddEmployee :show-dialog.sync="showDialog" @reload="getEmployeeListFn" />
    <AssignRole
      :show-role-dialog.sync="role.showRoleDialog"
      :user-id="role.userId"
    ></AssignRole>
  </div>
</template>

<script lang="ts">
import { Component, Mixins, Watch } from 'vue-property-decorator'
import { getEmployeeListAPI, delEmployeeAPI } from '@/api/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { hireTypeEnum } from '@/model/enum/employee'
import { IPage } from '@/model/interface/request'
import { formatDate } from '@/filters/index'
import { IEmployeeInfo } from '@/model/interface/employee'
import QRCode from 'qrcode'
import { checkEmployeeDel } from '@/mixins/index'

@Component({ name: 'Employee', components: { AddEmployee, AssignRole } })
export default class extends Mixins(checkEmployeeDel) {
  employeeList = [] // 数据列表
  showDialog = false
  role = {
    showRoleDialog: false,
    userId: ''
  }

  page: IPage = {
    page: 1, // 当前页码
    pagesize: 8, // 默认页容量
    pagesizes: [2, 4, 6, 8], // 页容量范围
    total: 200 // 总条数
  } // 分页数据

  previewArr: string[] = []

  // 分页数据有任何变化都重新获取列表
  @Watch('page', { deep: true })
  onPageChange() {
    this.getEmployeeListFn()
  }

  async created() {
    this.getEmployeeListFn()
    this.previewArr = [await QRCode.toDataURL('啥也没有')]
  }

  // 获取数据列表
  async getEmployeeListFn() {
    const { pagesize, page } = this.page
    const res = await getEmployeeListAPI({ page, size: pagesize })
    const { total, rows } = res
    this.employeeList = rows // 列表数据
    this.page.total = total // 总条数
    if ((this.page.pagesizes as Array<number>).indexOf(total) === -1) {
      (this.page.pagesizes as Array<number>).push(total) // 把总条数加入页容量可选项
    }
  }

  async previewFn(staffPhoto: string) {
    if (!staffPhoto) return
    const qrcode = await QRCode.toDataURL(staffPhoto)
    this.previewArr = [qrcode]
  }

  // 页容量改变
  handleSizeChange(val: number) {
    this.page.pagesize = val
  }

  // 页码改变
  handleCurrentChange(val: number) {
    this.page.page = val
  }

  /*
   * formatterDateFn(ow, column,cellValue,index)
   */
  // 格式化聘用形式
  formatterTypeFn(row: unknown, column: unknown, cellValue: number) {
    return hireTypeEnum[cellValue] || '未知形式'
  }

  // 删除员工
  delFn(id: string) {
    this.$confirm('此操作将永久删除, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        this.$message.success('删除成功!')
        delEmployeeAPI(id)
        this.page.page = 1 // 重置页码并刷新数据
      })
      .catch(() => this.$message.info('取消删除'))
  }

  // 分配角色
  handleShowRole(id: string) {
    this.role = {
      showRoleDialog: true,
      userId: id
    }
  }

  // 导出excle
  async exportExcleFn() {
    const { exportJson2Excel } = await import('@/utils/excel')
    const { rows } = await getEmployeeListAPI({
      page: 1,
      size: this.page.total
    })
    // console.log(rows)
    // 获取表头
    let header: any = Object.keys(rows[0])
    // console.log(header)
    // 获取数据
    const data = this.formatData(rows, header)
    // 表头改成中文
    header = header.map((keyEn: string) => this.$t('dictionary.' + keyEn))
    exportJson2Excel(header, data)
  }

  // 转二维数组
  formatData(list: Array<IEmployeeInfo>, header: Array<string>) {
    const data: Array<any> = []
    list.map((item: any) => {
      const arr: Array<any> = []
      header.map((head: string) => {
        const index = header.indexOf(head)
        // 格式化聘用形式
        if (head === 'formOfEmployment') {
          return (arr[index] = this.formatterTypeFn(null, null, item[head]))
        }
        // 格式化时间
        if (head.indexOf('ime') !== -1) {
          return (arr[index] = formatDate(item[head]))
        }
        // 其他数据直接返回
        arr[index] = item[head]
        return true
      })
      return data.push(arr)
    })
    return data
  }
}
</script>
